<?php

namespace App\Http\Middleware;

use App\common;
use App\server\JwtServer;
use App\server\RedisServer;

class TokenIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle($request, \Closure $next)
    {
        try {
            $tokenJwt = $request->header('authorization');//获取token
            $redis=RedisServer::createRedisObject();
            $redis->select(11);
            $tokenCache=$redis->get('jwtToken');
            if(empty($tokenJwt) || empty($tokenCache)) throw new \Exception('token为空或登录超时token失效');
            $token = substr($tokenJwt,7);
            $payload = JwtServer::JwtDecode($token);
            if(empty($payload['uid'])) throw new \Exception('用户id不能为空');
            return  $next($request);
        }catch (\Exception $exception){
            $response_data = common::fail(1,'', $exception->getMessage());
            return  response($response_data);
        }

    }
}
